package com.jokerpan.project.Handler;

import com.google.gson.Gson;
import com.jokerpan.project.Message.Msg;
import com.jokerpan.project.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationLogout implements LogoutSuccessHandler {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Gson gson;
    @Resource
    public RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String tokenHeader = request.getHeader(JwtUtils.TOKEN_HEADER);
        String token = tokenHeader.replace(JwtUtils.TOKEN_PREFIX, "");
        String key = "user_" + token;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        Msg result=Msg.success("注销成功");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(gson.toJson(result));
    }
}
